import React, { useRef, useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { Collapse, message, Empty, Layout, Row, Col, Card, Button, Input,Popover } from 'antd';
import services from '@/services/home';
import styles from './index.less';
import { useIntl,useModel,Link,useRequest,history,getLocale } from '@umijs/max';
import { MoreOutlined } from '@ant-design/icons';
import { start,loadMicroApp } from 'qiankun';
const { getSysUserCollectList,sysUserCollect,deletesysUserCollect} =
  services.UserController;

const HomePage: React.FC = () => {

  const { name,setName,clearCurrentTabList,allToken } = useModel('global');
  const { initialState, setInitialState }:any = useModel('@@initialState');
  const intl = useIntl();
  const [plist, setPlist] = useState([]);
  const [collectList, setCollectList] = useState([]);
  const [isShowApp, setIsShowApp] = useState(false);
  let microApp:any = null;
  // const {location}  = history;
  const location = useLocation();
  useEffect(() => {
    const _list:any = [];
    initialState?.appList.map((_item:any) =>{
      const _prinfo = {
        code: _item.code,
        name: formatMessageWithDefault(`menu.${_item.code}`, _item.name),
        description: _item.description,
        background: _item.background || _item.icon,
        appType: _item.appType,
        appTypeName: _item.appTypeName,
        type: _item.type,
      }
      _list.push(_prinfo);
    });
    initialState?.extApps.map((_item:any) =>{
      const _prinfo = {
        code: _item.code,
        name: formatMessageWithDefault(`menu.${_item.code}`, _item.name),
        description: _item.description,
        background: _item.background || _item.icon,
        appType: _item.appType,
        appTypeName: _item.appTypeName,
        type: _item.type,
        href: _item.href,
      }
      _list.push(_prinfo);
    });
    // setExtAppslist(initialState?.extApps || [])
    _list.length &&  setPlist(_list || []);
    getCList();
  
    microApp = loadMicroApp({
      name: 'tcpi', // 唯一 id
      // entry: '//localhost:3000/tcpi/', // html entry
      entry: 'http://test1.xhinkcar.cn/tcpi/', // 测试环境
      // entry: 'https://cop.thinkcar.cn/tcpi/', // 正式环境
      container: '#sub-app-tcpi',
      props: { 
        locale:getLocale(),
      },
    });
    microApp?.update?.({
      // microAppProps: {
      //   autoSetLoading: true,
      // },
    });
    return () => {
      microApp.unmount();
    };
    // start();
  }, []);
  useEffect(() => {
    console.log('========location',location.pathname);
    setIsShowApp(location.pathname.indexOf('/tcpi/index') != -1);
  }, [location]);

  const getCList = ()=>{
    getSysUserCollectList().then((res: any) => {
      if (res.appCode == 'S0000') {
        setCollectList(res.result || [])
      }
    });
  };
  const goHome = ()=>{
    // history.push('/');
    window.location.href = window.location.origin
  };
  const clickCollect = async (values:any)=>{
    console.log(values);
    const _fl = collectList.some((_item:any)=> _item.sysCodeCollect == values.name);
    if(_fl){
      message.success('已经收藏过了');
      return;
    }
    const hide = message.loading('');
    try {
      const _res = await sysUserCollect({sysCodeCollect:values.name});
      console.log(values,_res);
      if(_res.appCode == 'S0000'){
        message.success('成功');
        getCList();
      }else{
        message.error(_res.appMesg || '失败，请重试');
      }
      hide();
    } catch (error) {
      hide();
      message.error('失败，请重试');
    }
  };
  const gotoSystem = async (values:any,_type:any)=>{
    console.log(values);
    let _p = '';
    if(values.type == '10'){
      _p = values.code;
    }else if(values.type == '20'){
      let _url = values.href;
      _url.indexOf('?') != -1 ? _url=`${values.href}&token=${allToken}` : _url=`${values.href}?token=${allToken}`;
      window.open(_url);
    }else{
      _p = values.code;
    }
    // setInitialState((s:any) => ({ ...s, showMenu: true }));

    // history.push('/apphome/'+values.id);
    values.type != '20' && (window.location.href = window.location.origin+'/'+_p+'/home');
  };
  const gotoCollectSystem = (values:any)=>{
    const _fl = plist.find((_item:any)=> _item.code == values.sysCodeCollect);
    if(_fl){
      gotoSystem(_fl,'all')
    }
  };
  const getAppBg= (_id:any)=>{
    let _img = '';
    plist.map((_item:any)=>{
      if(_item.code == _id){
        _img =_item.background;
        // _img = _item.type == '20' ?   _item.href : _item.background;
      }
    });
    return _img;
  };
  const  formatMessageWithDefault =(id:any, defaultMessage:any, values = {})=> {  
    try {  
      // 尝试使用intl.formatMessage获取消息  
      return intl.formatMessage({ id, defaultMessage, ...values });  
    } catch (error) {  
      // 如果出现错误（这取决于你如何定义“错误”），则返回默认消息  
      return defaultMessage;  
    }  
  }

  return (
    <Layout className={styles.container}>
      <div>
        {
          isShowApp ?
        <Row gutter={[16, 24]} className={styles.tc_p_b_20} >
            {
              collectList.length ? collectList.map((_item:any)=>{
                return (
                  <Col
                    className="gutter-row"
                    key={'home_index_'+_item.id}
                    sm={2}
                  >
                    <Card bordered={false} hoverable className="tc_tcpi_1"  onClick={()=>gotoCollectSystem(_item)} >
                    <img alt="" src={getAppBg(_item.sysCodeCollect)} className={styles.tc_h_1_1} />
                    <p className='tc_tcpi_1_1'>
                      <Popover content={_item.sysCodeCollectName} placement="topLeft" >
                      {_item.sysCodeCollectName}
                      </Popover>
                    </p>
                    </Card>
                  </Col>
                )
              }):
              ""
            }
            <Col
                    className="gutter-row"
                  sm={2}
                  >
                    <Card bordered={false} hoverable className="tc_tcpi_1" onClick={goHome} >
                    <img alt="" src={`${initialState?.staticImg}cop/cop_2.png`} className={styles.tc_h_1_1} />
                      <p className='tc_tcpi_1_1'>
                      <Popover content={intl.formatMessage( { id: 'component.h_3'})} placement="topLeft" >
                      {intl.formatMessage( { id: 'component.h_3'})}
                      </Popover>
                    </p>
                    </Card>
                  </Col>
          </Row>
          :""
          }
        <div id='sub-app-tcpi'></div>
      </div>
    </Layout>
  );
};

export default HomePage;


